import { h, ref, toRaw } from 'vue';
import { useFuncStore } from '@/store/func-store';

import { GetListBaseConfig, ListFieldConfigGet } from '@/api';
import * as components from '../views/config/components';
import { ModalConfig, MenuConfig } from '@/views/config/hooks/menu-config';
import { Modal, Drawer, Button } from '@jecloud/ui';
import { useRouter } from '@common/router';
import { ConfigRouteName } from '@/router';
import { useMicroStore } from '@common/store/micro-store';
import { showFuncQuerys } from '@jecloud/func';
import { getAxiosBaseURL, getBodyWidth } from '@jecloud/utils';
import { useGlobalStore } from '@common/store/global-store';

export function useFuncConfig() {
  /**
   * 打开功能配置
   * @param {Object} param
   * @param {String} param.key 面板key
   * @param {String} param.funcId 功能ID
   * @param {String} param.code 字段，列的编码
   * @param {String} param.bean 字段，列的业务数据
   * @param {String} param.props 组件配置
   */
  const showFuncConfig = ({ route = false, key = 'FuncMain', funcId, bean, code, props = {} }) => {
    if (!funcId) {
      Modal.alert('请选择功能数据！');
      return;
    }
    const funcStore = useFuncStore();
    const { activePlan } = useGlobalStore();
    // 路由打开
    if (route && key === 'FuncMain') {
      const router = useRouter();
      router.push({ name: ConfigRouteName, params: { funcId } });
      return;
    }
    const newMenuConfig = [];
    MenuConfig.forEach((item) => {
      item.children.forEach((item_) => {
        newMenuConfig.push(item_);
      });
    });

    const config = newMenuConfig.find((item) => item.key === key);
    let activeKey = '';
    if (['FuncFormBase', 'FuncFormFields', 'FuncFormDesign'].includes(key)) {
      activeKey = 'FuncFormLayout';
    }
    if (['FuncListBase', 'FuncListFields'].includes(key)) {
      activeKey = 'FuncListLayout';
    }
    initConfigData({ funcId, code, key, bean })
      .then((data) => {
        const opts = {
          title: config?.text,
          ...ModalConfig.default,
          ...ModalConfig[key],
        };
        if (opts.drawer) {
          const refEl = ref();
          const drawPanel = Drawer.show({
            ...opts,
            bodyStyle: { padding: 0 },
            extraSlot({ visible }) {
              // 保存
              const save = ({ close }) => {
                refEl.value?.doSave?.()?.then?.(() => {
                  close && (visible.value = false);
                });
              };
              // 保存关闭
              const saveClose = () => {
                save({ close: true });
              };
              // 放大逻辑
              const changeMax = () => {
                drawPanel.changeWidth(getBodyWidth() * 0.5);
              };
              const changeMaxWidthEnter = (e) => {
                e.target.style.color = '#000';
                return false;
              };
              const changeMaxWidthLeave = (e) => {
                e.target.style.color = '';
                return false;
              };

              return [
                <div
                  onClick={changeMax}
                  onMouseenter={changeMaxWidthEnter}
                  onMouseleave={changeMaxWidthLeave}
                  style="display: inline-block;cursor: pointer;font-size: 16px;padding: 3px 20px"
                >
                  <i class="fal fa-angles-left"></i>
                </div>,
                <Button type="primary" onClick={save} style="margin-right:6px;">
                  保存
                </Button>,
                <Button type="primary" onClick={saveClose}>
                  保存关闭
                </Button>,
              ];
            },
            content() {
              return h(components[key], { ref: refEl, drawer: true, ...props, ...data });
            },
          });
        } else if (opts.micro) {
          const microStore = useMicroStore();
          const {
            FUNCINFO_FUNCNAME,
            FUNCINFO_FUNCCODE,
            FUNCINFO_TABLENAME,
            SY_PRODUCT_ID,
            SY_PRODUCT_CODE,
            SY_PRODUCT_NAME,
            JE_CORE_FUNCINFO_ID,
            JE_CORE_RESOURCETABLE_ID,
          } = data.funcBean;
          // 流程配置
          if (key == 'WorkflowCongig') {
            const funcData = {
              funcName: FUNCINFO_FUNCNAME, //功能名称
              funcCode: FUNCINFO_FUNCCODE,
              funcId: JE_CORE_FUNCINFO_ID, //功能Id
              tableCode: FUNCINFO_TABLENAME, //功能对应资源表的code
              SY_PRODUCT_ID, //功能对应产品的id
              SY_PRODUCT_CODE, //功能对应产品的code
              SY_PRODUCT_NAME, //功能对应产品的名称
            };
            microStore.emitMicro('JE_CORE_WORKFLOW', 'workflow-init', { funcData: funcData });
          }
          if (key == 'DataLimitConfig') {
            microStore.emitMicro('JE_CORE_RBAC_DATA', 'data-authority-init', {
              funcCode: FUNCINFO_FUNCCODE,
              funcId: JE_CORE_FUNCINFO_ID,
            });
          }
          if (key == 'openTable') {
            if (!JE_CORE_RESOURCETABLE_ID) {
              Modal.alert('资源表不存在！', 'error');
              return false;
            }
            const { id } = funcStore.product;
            window.open(
              `${getAxiosBaseURL()}/#/${activePlan}/app/JE_CORE_TABLE?productId=${id}&id=${JE_CORE_RESOURCETABLE_ID}`,
            );
          }

          if (key == 'openFunction') {
            if (!JE_CORE_FUNCINFO_ID) {
              Modal.alert('功能不存在', 'error');
              return false;
            }
            const { id } = funcStore.product;
            window.open(
              `${getAxiosBaseURL()}/#/${activePlan}/app/JE_CORE_FUNCTION?productId=${id}&id=${JE_CORE_FUNCINFO_ID}`,
            );
          }
        } else if (opts.openTune) {
          if (key == 'FuncSqlBuilder') {
            showFuncQuerys({
              funcId: funcId,
            });
          }
        } else {
          const modalEle = ref(null);
          // 初始选中值
          const onShow = function ({ $modal }) {
            modalEle.value = $modal;
          };
          Modal.window({
            ...opts,
            bodyStyle: {
              padding: '0px',
            },
            className: key == 'FuncListeners' ? 'listener-modal' : '',
            onShow,
            content() {
              return h(components[activeKey || key], {
                ...props,
                modalEle: modalEle.value,
                ...data,
                activedKey: activeKey ? key : '',
              });
            },
          });
        }
      })
      .catch((err = { message: '' }) => {
        Modal.alert(err.message);
      });
  };
  return { showFuncConfig };
}

// 初始化功能数据
export const initConfigData = ({ funcId, code, key, bean }) => {
  const funcStore = useFuncStore();
  return new Promise((resolve, reject) => {
    return GetListBaseConfig({ pkValue: funcId })
      .then((data) => {
        delete data.$TABLE_CODE$;
        data.id = data.JE_CORE_FUNCINFO_ID;
        data.code = data.FUNCINFO_FUNCCODE;
        data.text = data.FUNCINFO_FUNCNAME;
        data.tableCode = 'JE_CORE_FUNCINFO';
        funcStore.funcBean = data;
        return data;
      })
      .then((data) => {
        // 产品信息
        funcStore.setProduct({
          id: data.SY_PRODUCT_ID,
          code: data.SY_PRODUCT_CODE,
          name: data.SY_PRODUCT_NAME,
        });
        // 配置数据
        const props = { funcBean: data };
        switch (key) {
          case 'FuncListField':
            initColumnData({ funcId, code }).then((_bean) => {
              const dataBean = bean ? toRaw(bean) : _bean;
              if (dataBean) {
                props.bean = dataBean;
                resolve(props);
              } else {
                reject({ message: '未找到列表字段配置！' });
              }
            });
            break;
          case 'FuncFormField':
            initFieldData({ funcId, code }).then((_bean) => {
              const dataBean = bean ? toRaw(bean) : _bean;
              if (dataBean) {
                props.bean = dataBean;
                resolve(props);
              } else {
                reject({ message: '未找到表单字段配置！' });
              }
            });
            break;
          default:
            resolve(props);
            break;
        }
      });
  });
};

/**
 * 初始化字段数据
 * @param {*} param0
 * @returns
 */
function initFieldData({ funcId, code }) {
  const funcStore = useFuncStore();
  const params = {
    tableCode: 'JE_CORE_RESOURCEFIELD',
    j_query: JSON.stringify({
      custom: [
        {
          code: 'RESOURCEFIELD_FUNCINFO_ID',
          value: funcId,
          type: '=',
        },
      ],
      order: [{ code: 'SY_ORDERINDEX', type: 'ASC' }],
    }),
    funcId,
    limit: -1,
  };
  return ListFieldConfigGet(params).then((res) => {
    // 业务bean
    let bean;
    // 分组框
    funcStore.groupFields = [];
    // 依附字段
    funcStore.attachFields = [];
    res.data.rows.forEach((item) => {
      const field = {
        label: item.RESOURCEFIELD_NAME,
        value: item.RESOURCEFIELD_CODE,
      };
      item.RESOURCEFIELD_XTYPE != 'fieldset' && funcStore.attachFields.push(field);
      if (item.RESOURCEFIELD_XTYPE == 'fieldset') {
        funcStore.groupFields.push(field);
      }
      if (item.RESOURCEFIELD_CODE === code) {
        bean = item;
      }
    });
    return bean;
  });
}

/**
 * 初始化列段数据
 * @param {*} param0
 * @returns
 */
function initColumnData({ funcId, code }) {
  const funcStore = useFuncStore();
  const params = {
    tableCode: 'JE_CORE_RESOURCECOLUMN',
    funcId,
    limt: -1,
    j_query: JSON.stringify({
      custom: [
        {
          code: 'RESOURCECOLUMN_FUNCINFO_ID',
          value: funcId,
          type: '=',
        },
      ],
      order: [{ code: 'SY_ORDERINDEX', type: 'ASC' }],
    }),
  };

  return ListFieldConfigGet(params).then((res) => {
    // 业务bean
    let bean;
    // 多表头
    funcStore.groupColumns = [];
    res.data.rows.forEach((item) => {
      if (item.RESOURCECOLUMN_XTYPE === 'morecolumn') {
        funcStore.groupColumns.push({
          value: item.RESOURCECOLUMN_CODE,
          label: item.RESOURCECOLUMN_NAME,
        });
      }
      if (item.RESOURCECOLUMN_CODE === code) {
        bean = item;
      }
    });
    return bean;
  });
}
